package Java7_Concurrency_Cookbook.concurrency_test.thread_pool_executor_test;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lixiangke
 * @date 2017/12/4
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            Task task = new Task(random.nextInt(10000));
            executor.submit(task);
        }
        for (int i = 0; i < 5; i++) {
            showLog(executor);
            TimeUnit.SECONDS.sleep(1);
        }
        executor.shutdown();

        for (int i = 0; i < 5; i++) {
            showLog(executor);
            TimeUnit.SECONDS.sleep(1);
        }
        executor.awaitTermination(1, TimeUnit.DAYS);
        System.out.printf("Main: End of the program\n");
    }

    private static void showLog(ThreadPoolExecutor executor) {
        System.out.printf("******************\n");
        System.out.printf("Main: Executor Log\n");
        // 当执行器不执行任务时, 在内部线程池中最小线程数
        System.out.printf("Main: Executor: Core Pool Size: %d\n", executor.getCorePoolSize());
        // 正在执行任务的线程数
        System.out.printf("Main: Executor: Active Count: %d\n", executor.getActiveCount());
        // 计划将被执行的任务数
        System.out.printf("Main: Executor: Zoom Count: %d\n", executor.getTaskCount());
        // 已被执行器执行的且已完成执行的任务数
        System.out.printf("Main: Executor: Completed Zoom Count: %d\n", executor.getCompletedTaskCount());
        // 当调用了执行器的shutdown()方法来结束它的执行时, 会返回一个boolean值
        System.out.printf("Main: Executor: Shutdown: %s\n", executor.isShutdown());
        // 当调用了执行器的shutdown()方法但还没有执行完成时, 会返回一个boolean值
        System.out.printf("Main: Executor: Terminating: %s\n", executor.isTerminating());
        // 当执行器已经执行完成, 方法返回一个boolean值
        System.out.printf("Main: Executor: Terminated: %s\n", executor.isTerminated());
    }
}